import {
  getArticleSortList as _getArticleSortList,
  getArticleList as _getArticleList,
} from '../../config/api'
import { get } from '../../utils/request'

Page({
  data: {
    scrollLeft: 200,
    active: 0, // 当前选中
    articleSortList: [], // 分类列表
    articleList: [], // 文章列表
    selectedTitle: '0',
    page: 1,
    size: 10,
    totalPage: 0, // 总页数
  },
  // 事件处理函数
  tabClick(val) {
    const { tab, index } = val.currentTarget.dataset
    if (tab === this.data.active) {
      return
    }
    this.setData({
      active: tab,
      selectedTitle: index,
      articleList: [],
      page: 1,
      size: 10,
    })
  },
  articleDetial(val) {
    let { item } = val.currentTarget.dataset
    if (item) {
      wx.navigateTo({
        url: '../articleDetail/index?id=' + item,
      })
    }
  },
  onLoad() {
    this.getArticleSortList()
  },
  // 获取文章分类
  getArticleSortList: async function () {
    const res = await get(_getArticleSortList)
    if (res.httpStatus === 200) {
      this.setData({
        articleSortList: res.data,
        active: res.data[0].id,
      })
      this.getArticleList(res.data[0].id)
    }
  },
  bindChange: function (e) {
    const { articleSortList } = this.data
    const selectedTitle = e.detail.current
    // 上方标题联动
    this.setData({
      scrollLeft: selectedTitle * 80,
    })
    const id = articleSortList[selectedTitle].id
    this.setData({
      active: id,
      articleList: [],
      selectedTitle,
      page: 1,
      size: 10,
      totalPage: 0,
    })

    this.getArticleList(id)
  },
  // 获取文章列表
  getArticleList: async function (id) {
    const { page, size } = this.data
    const res = await get(_getArticleList, {
      dictId: id,
      page,
      size,
      isShowRecommend: 1,
    })
    let newList = this.data.articleList
    if (res.httpStatus === 200) {
      if (res.data.records.length === 0) {
        wx.showToast({
          title: '暂无文章',
          icon: 'none',
        })
        return
      }
      newList.push(...res.data.records)
      this.setData({
        articleList: newList,
        totalPage: res.data.pages,
      })
    }
  },
  //监听是否滑到底部
  nextPage: function () {
    let { page, totalPage } = this.data
    if (page === totalPage) {
      return
    }
    page += 1
    this.setData({
      page: page,
    })
    this.getArticleList(this.data.active)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
